<template>
  <div class="merchant-layout">
    <el-container>
      <el-aside width="200px">
        <div class="logo">人格魅力餐厅</div>
        <el-menu
          :default-active="activeIndex"
          class="el-menu-vertical"
          router
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
        >
          <el-menu-item index="/merchant/dish">
            <el-icon><Food /></el-icon>
            <span>菜品管理</span>
          </el-menu-item>
          <el-menu-item index="/merchant/order">
            <el-icon><List /></el-icon>
            <span>订单管理</span>
          </el-menu-item>
          <el-menu-item index="/merchant/inventory">
            <el-icon><Box /></el-icon>
            <span>库存管理</span>
          </el-menu-item>
          <el-menu-item index="/merchant/feedback">
            <el-icon><ChatDotRound /></el-icon>
            <span>评价管理</span>
          </el-menu-item>
          <el-menu-item index="/merchant/users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="/merchant/statistics">
            <el-icon><DataAnalysis /></el-icon>
            <span>数据统计</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container class="main-container">
        <el-header>
          <div class="header-container">
            <div class="breadcrumb">
              <el-breadcrumb separator="/">
                <el-breadcrumb-item>{{ getPageTitle() }}</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <div class="user-info">
              <template v-if="isLoggedIn">
                <span class="welcome-text">欢迎, {{ username }}</span>
                <el-button size="small" type="primary" plain @click="showChangePassword">修改密码</el-button>
                <el-button size="small" type="danger" plain @click="confirmLogout">退出登录</el-button>
              </template>
              <template v-else>
                <el-button size="small" type="primary" plain @click="$router.push('/merchant/login')">登录</el-button>
              </template>
            </div>
          </div>
        </el-header>
        <el-main>
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>

  <!-- 修改密码对话框 -->
  <el-dialog
    v-model="passwordDialogVisible"
    title="修改密码"
    width="30%"
    :close-on-click-modal="false"
  >
    <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword" :loading="passwordLoading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Food, List, Box, ArrowDown, ChatDotRound, User, DataAnalysis } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { merchantApi } from '../api/index'

const route = useRoute()
const router = useRouter()

const activeIndex = computed(() => route.path)
const isLoggedIn = ref(false)
const username = ref('')

// 修改密码相关
const passwordDialogVisible = ref(false)
const passwordLoading = ref(false)
const passwordFormRef = ref<FormInstance>()

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (passwordForm.confirmPassword !== '') {
      if (passwordFormRef.value) {
        passwordFormRef.value.validateField('confirmPassword', () => {})
      }
    }
    callback()
  }
}

const validatePass2 = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const passwordRules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
})

// 获取页面标题
const getPageTitle = () => {
  const path = route.path
  if (path.includes('/dish')) return '菜品管理'
  if (path.includes('/order')) return '订单管理'
  if (path.includes('/inventory')) return '库存管理'
  if (path.includes('/feedback')) return '评价管理'
  if (path.includes('/users')) return '用户管理'
  if (path.includes('/statistics')) return '数据统计'
  return '订单管理' // 默认显示订单管理
}

// 模拟登录状态
const checkLoginStatus = () => {
  const merchant = localStorage.getItem('merchant')
  if (merchant) {
    isLoggedIn.value = true
    username.value = JSON.parse(merchant).name
  } else {
    isLoggedIn.value = false
    username.value = ''
  }
}

// 显示修改密码对话框
const showChangePassword = () => {
  // 重置表单
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      // 确认两次输入的密码一致
      if (passwordForm.newPassword !== passwordForm.confirmPassword) {
        ElMessage.error('两次输入的密码不一致')
        return
      }

      passwordLoading.value = true
      try {
        console.log('调用商家修改密码API')
        // 调用后端API修改密码
        await merchantApi.changePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })

        // 密码修改成功后，更新本地存储的商家信息
        const merchant = JSON.parse(localStorage.getItem('merchant') || '{}')

        // 获取最新的商家信息
        const res = await merchantApi.getInfo()
        localStorage.setItem('merchant', JSON.stringify(res.data))

        ElMessage.success('密码修改成功')
        passwordDialogVisible.value = false

        // 清空表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
      } catch (error: any) {
        console.error('修改密码失败:', error)
        ElMessage.error(error.message || '密码修改失败')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 确认退出登录
const confirmLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      logout()
      ElMessage({
        type: 'success',
        message: '已安全退出登录',
      })
    })
    .catch(() => {
      // 用户取消退出
    })
}

// 退出登录
const logout = () => {
  localStorage.removeItem('merchant')
  localStorage.removeItem('token')
  isLoggedIn.value = false
  username.value = ''
  router.push('/merchant/login')
}

// 页面加载时检查登录状态
checkLoginStatus()
</script>

<style scoped>
.merchant-layout {
  height: 100vh;
  width: 100vw;
  display: flex;
  overflow: hidden;
}

.el-container {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

.main-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.el-aside {
  background-color: #545c64;
  color: #fff;
}

.logo {
  height: 60px;
  line-height: 60px;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: #fff;
  background-color: #304156;
}

.el-menu-vertical {
  border-right: none;
  margin-right: 0; /* 移除右侧边距 */
  padding-right: 0; /* 移除右侧内边距 */
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #dcdfe6;
  padding: 0 20px;
}

.header-container {
  display: flex;
  align-items: center;
  height: 60px;
}

.breadcrumb {
  flex: 1;
  height: 60px; /* 确保高度与header一致 */
  display: flex;
  align-items: center; /* 垂直居中 */
}

.user-info {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.username-text, .welcome-text {
  margin-right: 15px;
  font-weight: 500;
  color: #606266;
}

.user-info .el-button {
  margin-left: 8px;
  border-radius: 4px;
  font-weight: 500;
  padding: 6px 12px;
}

.el-main {
  padding: 20px;
  background-color: #f5f7fa;
  overflow-y: auto;
  height: calc(100vh - 60px); /* 只减去header的高度 */
}


</style>
